const Koa = require("koa");
const parser = require("koa-parser");
const router = require("koa-router")();
const session = require("koa-session");
const views = require("koa-views");
const static = require("koa-static");
const nunjucks = require("nunjucks");
const app = new Koa();


app.keys=["2370218992"];

//渲染模板引擎
app.use(views(__dirname+"/views" ,{
 map:  {html :"nunjucks"}
}));

//引入session模块
app.use(session({
    maxAge :10*1000 
},app))

app.use(static(__dirname+"/public"))

app.use(parser());

app.use(router.routes());

//首页
router.get("/",async(ctx,next)=>{
  await ctx.render("login.html")
})

router.get("/login",async(ctx,next)=>{
    if(ctx.session.user){
        await ctx.redirect("/home")
    }else{
        await ctx.render("login")
    }
})


//主页
router.get("/home",async(ctx,next)=>{
    if(ctx.session.user){
        await ctx.render("home",{
            title :"这是我的主页"
        })
    }
    else{
        await ctx.render("login")
    }
    
})

//处理路由post登录请求
router.post("/login",async(ctx,next)=>{
    let username = ctx.request.body.username;
    let password = ctx.request.body.password;
    if(username === "admin123" && password === "2370218992"){
        ctx.session.user="milu"
        ctx.redirect("/home")
    }  
    else{
        ctx.body = "账号或密码错误"
    }
})

//处理post注册的请求
router.post("/resigner",async(ctx,next)=>{
    let password1 = ctx.request.body.password1;
    let password2 = ctx.request.body.password2;
    if(password1 === password2 && password1 != "" && password2 != ""){
        ctx.redirect("/home")
    }else{
        ctx.body ="两次输入密码不一样"

    }
        
})

//注册请求
router.get("/resigner",async(ctx,next)=>{
    await ctx.render("resigner.html");
})


//注销
router.get("/logout",async(ctx,next)=>{
    ctx.session.user ="";
   await ctx.redirect("/login");
})


//上一层阶级

router.get("/goback",async(ctx,next)=>{
    ctx.redirect("/login")
})


app.listen(3000,()=>{
    console.log("服务器运行的地址是:http://127.0.0.1:3000");
})





